import { Effect } from '../../typings';
import { Reducer } from 'redux';
import { getBtnPermission, getMenuInfo } from '../services/loginServices';
import { hehLocalStorage } from '@/utils/utils';

export interface ModelType {
  namespace: string;
  state: MainLayoutModelType;
  effects: {
    setBtnPermission: Effect;
  };
  reducers: {
    setLoading: Reducer;
    setUserInfo: Reducer;
  };
}

export interface MainLayoutModelType {
  btnPermissionLoading: boolean;
  userInfo: any;
}

const Model: ModelType = {
  namespace: 'globalModel',

  state: {
    btnPermissionLoading: false,
    userInfo: {},
  },

  effects: {
    *setBtnPermission({ payload }, { call, put }) {
      if (!hehLocalStorage.hasItem(payload.path)) {
        yield put({
          type: 'setLoading',
          payload: true,
        });
        if (payload.id === 1102 || payload.id === 1103 || payload.id === 1104) {
          payload.id = 1101;
        }

        const response = yield call(getBtnPermission, payload.id);
        const arr: any = [];
        response.forEach((n: any) => {
          arr.push(n.permission);
        });
        hehLocalStorage.setItem(payload.path, arr);
        yield put({
          type: 'setLoading',
          payload: false,
        });
      }
    },
  },

  reducers: {
    setLoading(state, { payload }) {
      return {
        ...state,
        btnPermissionLoading: payload,
      };
    },
    setUserInfo(state, { payload }) {
      return {
        ...state,
        userInfo: payload,
      };
    },
  },
};

export default Model;
